<template>
  <form class="search-bar">
    <input
      v-model="val"
      type="text"
      placeholder="搜索超市商品"
    />
    <a
      v-show="val"
      href="javascript:;"
      class="close"
      @click="clear"
    >
      <icon name="guanbi" :size="40" />
    </a>
    <template>
      <div v-show="val" class="address-list">
        <ul>
          <li
            v-for="(item, index) in addresses"
            :key="index"
            @click="select(item)"
          >
            <h2>{{ item.name }}</h2>
            <p>{{ item.district }}</p>
          </li>
        </ul>
      </div>
    </template>
  </form>
</template>

<script>
import { autoComplete } from '@/utils/map'

export default {
  name: 'SearchBar',
  props: {
    value: String,
  },
  data () {
    return {
      val: this.value || '',
      addresses: []
    }
  },
  watch: {
    val (newValue) {
      this.autoComplete()
    },
  },
  methods: {
    async autoComplete () {
      const res = await autoComplete(this.val)
      console.log(res)
      this.addresses = res.tips
    },
    clear () {
      this.val = ''
      this.$emit('onClear')
    },
    select (data) {
      this.$store.commit('user/SET_LOCATION', {
        name: data.name,
        district: data.district,
        address: data.address,
        adcode: data.adcode,
        location: data.location
      })
      this.$router.push('/home')
    }
  }
}
</script>

<style lang="scss" scoped>
.search-bar {
  @include wh(100%, 98px);
  @include flex(row, center, center);
  @include border1px(bottom, #E2E2E2);
  background: #fff;
  flex-shrink: 0;
  position: relative;
  input {
    @include wh(auto, 64px);
    flex: 1;
    margin: 0 30px;
    padding: 0 40px;
    border-radius: 64px;
    background: #F6F6F6;
    border: 0;
    outline: none;
  }
  .close {
    position: absolute;
    right: 40px;
  }
}
.address-list {
  position: fixed;
  width: 100%;
  top: 98px;
  bottom: 0;
  overflow: auto;
  ul {
    li {
      padding: 20px;
      line-height: 1.5;
      h2 {
        font-size:28px;
        color: #333;
        font-weight: none;
      }
      p {
        font-size:28px;
        color: #666;
        font-weight: none;
      }
    }
  }
}
</style>
